﻿using System;
using System.ComponentModel;
using Microsoft.VisualStudio.TestTools.WebTesting;
using Microsoft.VisualStudio.TestTools.WebTesting.Rules;

namespace WebAndLoadTestPluginsAndRules
{
    /// <summary>
    /// This class converts any comments you enter during recording to a transaction  
    /// </summary>
    public class CovertRecordedCommentsToTransactions : WebTestRecorderPlugin
    {
        public override void PostWebTestRecording(object sender, PostWebTestRecordingEventArgs e)
        {
            for (int i = 0; i < e.RecordedWebTest.Items.Count; i++)
            {
                //get the item and see if it is a comment
                WebTestItem item = e.RecordedWebTest.Items[i];
                Comment c = item as Comment;
                if (c != null)
                {
                    //if it is a comment create a transaction
                    TransactionTimer tt = new TransactionTimer();

                    //set name of transaction to the comment text
                    tt.Name = c.CommentText;

                    //now add all items up until next comment
                    int j = i + 1;
                    while (j < e.RecordedWebTest.Items.Count)
                    {
                        WebTestItem nextItem = e.RecordedWebTest.Items[j];

                        //if the item is not a comment move it into the transaction
                        if (!(nextItem is Comment))
                        {
                            tt.Items.Add(nextItem);
                            e.RecordedWebTest.Items.RemoveAt(j);
                        }
                        else
                        {
                            break;
                        }
                    }

                    //add the transaction to the web test
                    e.RecordedWebTest.Items.Insert(j, tt);

                    //remove the comment from the web test
                    e.RecordedWebTest.Items.RemoveAt(i);

                    //indicate that the web test has been modified
                    e.RecordedWebTestModified = true;

                }
            }

        }
    }
}
